package com.yizisu.library.ad.impl.applovin

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.applovin.mediation.ads.MaxRewardedAd
import com.applovin.sdk.AppLovinMediationProvider
import com.applovin.sdk.AppLovinSdk
import com.applovin.sdk.AppLovinSdkConfiguration
import com.facebook.ads.AdSettings
import com.weilele.mvvm.MvvmConf
import com.weilele.mvvm.mainHandler
import com.yizisu.library.ad.IAd
import com.yizisu.library.ad.IAdRewardStatus
import com.yizisu.library.ad.IAdStatus
import com.yizisu.library.ad.impl.BaseAd
import com.yizisu.library.ad.impl.ironsource.IronSourceImpl
import com.yizisu.login.R

class ApplovinImpl(activity: AppCompatActivity) : BaseAd() {

    companion object {
        private var applovinImpl: ApplovinImpl? = null
        internal fun initSdk(context: Context, block: Function0<Unit>) {
            // Please make sure to set the mediation provider value to "max" to ensure proper functionality
            AppLovinSdk.getInstance(context).mediationProvider = AppLovinMediationProvider.MAX
            AdSettings.setDataProcessingOptions(arrayOf<String>())
            AppLovinSdk.getInstance(context)
                .initializeSdk { configuration: AppLovinSdkConfiguration ->
                    // AppLovin SDK is initialized, start loading ads
                    // sdk初始化完毕
                    block.invoke()
                }
        }

        internal fun getInstance(activity: AppCompatActivity): ApplovinImpl {
            var ad = applovinImpl
            if (ad != null) {
                return ad
            }
            ad = ApplovinImpl(activity)
            applovinImpl = ad
            activity.lifecycle.addObserver(ad)
            return ad
        }
    }

    private val rewardedAd by lazy {
        MaxRewardedAd.getInstance(activity.getString(R.string.applovin_reward_ad), activity)
    }
    private val rewardedAdListener by lazy { ApplovinVideoListener(rewardedAd) }


    override fun onCreate() {
        super.onCreate()
        rewardedAd.setListener(rewardedAdListener)
        rewardedAd.loadAd()
        rewardedAdListener.statusData.postValue(IAdStatus.Loading)
    }

    /**
     * 等待广告加载
     */
    private var waitVideoAdRunnable: Runnable? = null

    /**
     * 广告加载结果回调
     */
    private var waitVideoAdObserver: Observer<IAdStatus>? = null

    override fun showVideoAd(
        wait: Long,
        life: LifecycleOwner?,
        rewardListener: (IAdRewardStatus) -> Unit
    ): Boolean {
        //取消之前的等待，如果有
        cancelWaitVideoAd()
        if (rewardedAd.isReady) {//广告可用
            rewardedAdListener.rewardListener = rewardListener
            rewardedAd.showAd()
            return true
        } else {//广告不可用
            if (rewardedAdListener.statusData.value == IAdStatus.Error) {
                rewardedAd.loadAd()
            }
            if (wait >= 0 && life != null) {//等待加载，wait的等待的超时时间
                val run = Runnable {
                    checkVideoAd(rewardListener)
                    cancelWaitVideoAd()
                }
                waitVideoAdRunnable = run
                val observer = Observer<IAdStatus> {
                    if (it is IAdStatus.Success ||
                        it is IAdStatus.Error
                    ) {
                        waitVideoAdRunnable?.run()
                    }
                }
                waitVideoAdObserver = observer
                mainHandler.postDelayed(run, wait)
                rewardedAdListener.statusData.postValue(IAdStatus.Loading)
                rewardedAdListener.statusData.observe(life, observer)
            } else {
                rewardListener.invoke(IAdRewardStatus.NoAd)
            }
            return false
        }
    }

    override fun cancelWaitVideoAd() {
        waitVideoAdRunnable?.let {
            mainHandler.removeCallbacks(it)
        }
        waitVideoAdObserver?.let {
            rewardedAdListener.statusData.removeObserver(it)
        }
        waitVideoAdRunnable = null
        waitVideoAdObserver = null
    }

    private fun checkVideoAd(rewardListener: (IAdRewardStatus) -> Unit) {
        if (rewardedAd.isReady) {
            rewardedAdListener.rewardListener = rewardListener
            rewardedAd.showAd()
        } else {
            rewardListener.invoke(IAdRewardStatus.NoAd)
        }
    }

    override fun showOfferWall(): Boolean {
        return IronSourceImpl.showOfferWall()
    }

    override fun getOfferWallCredits() {
        IronSourceImpl.getOfferWallCredits()
    }

    override fun setOnOfferWallListener(listener: ((Int, Int, Boolean) -> Boolean)?) {
        IronSourceImpl.setOnOfferWallListener(listener)
    }

    override fun onDestroy() {
        super.onDestroy()
        applovinImpl = null
        rewardedAd.destroy()
        cancelWaitVideoAd()
    }
}